package net.zjitc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.zjitc.pojo.User;
import net.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @autho dell
 * @date 2018/5/22
 */
@Controller
public class UserController {

    private static final Integer pageSize = 10;
    @Autowired
    UserService userService;
    @RequestMapping(value = "/index")
    public String index(){
        return "login";
    }
    @RequestMapping(value = "/login")
    public String login(User user,HttpSession session){
          User u  = userService.login(user);
          if (u != null){
              session.setAttribute("user",u);
          }
           return "index";
    }

    @RequestMapping(value = "/findAll")
    public String findAll(Model model){
        List<User> list = userService.findAll();
        model.addAttribute("list",list);
        return "list";
    }

    @RequestMapping(value = "/register")
    public String register(User user){
         userService.insert(user);
        return "redirect:/findAll.do";
    }

    @RequestMapping(value = "/jsonLogin")
    @ResponseBody
    public Map<String ,Object> jsonLogin( User user){
        Map<String ,Object> map = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        User u  = userService.login(user);
        if (u!= null){
            map.put("user",u);
            map.put("success",true);
        }else {
            map.put("success",false);
        }
        return map;
    }

    @RequestMapping(value = "/postLogin")
    @ResponseBody
    public Map<String ,Object> postLogin( User user) throws JsonProcessingException {
        Map<String ,Object> map = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        User u  = userService.login(user);
        if (u!= null){
            map.put("user",u);
            map.put("success",true);
        }else {
            map.put("success",false);
        }
        return map;
       // return mapper.writeValueAsString(map);
       // return "index"; /*返回此页面内容*/
    }

    @RequestMapping(value = "/findPage")
    public String findPage(Model model,Integer page){

        PageInfo<User> pageInfo = userService.findPage(page,pageSize);
        model.addAttribute("pageInfo",pageInfo);
        return "pageList";
    }
}
